package cn.ybk.练习1;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class Test1 {
    public static void main(String[] args) {
        List<int[]> list = new ArrayList<>();

        for(int i=0;i<5;i++){
            int[] arr = new int[(int)(Math.random()*10+3)];
            for(int k = 0;k<arr.length;k++){
                arr[k]=(int)(Math.random()*20);
            }
            list.add(arr);
        }

        int sum = 0;
        for(int[] arr : list){
            for(int m : arr){
                sum+=m;
            }
        }
        System.out.println("sum="+sum);


        //存放每组数组的和（线程安全）
        Vector<Integer> vector = new Vector<>();
        //将每组数组求和的线程
        for (int i = 0;i<list.size();i++){

            int[] arr = list.get(i);
            new Thread(()->{
                int s = 0;
                for (int j = 0;j<arr.length;j++){
                    s+=arr[j];
                    Thread.yield();

                }
                vector.add(s);
            }).start();
        }



        //将每组数组的和再进行求和
        new Thread(){
            public void run(){
                while(vector.size() < list.size()){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int s = 0;
                for(int n : vector){
                    s+=n;
                }
                System.out.println("总和："+s);
            }
        }.start();

    }
}
